from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required
import subprocess
import socket
from datetime import datetime
import os
from .utils import validate_ip

network_bp = Blueprint('network', __name__)

@network_bp.route('/')
@login_required
def index():
    return render_template('network/index.html')

@network_bp.route('/ping', methods=['POST'])
@login_required
def ping():
    ip = request.form.get('ip', '').strip()
    count = request.form.get('count', '4').strip()
    
    if not validate_ip(ip):
        return jsonify({'error': '无效的IP地址'}), 400
    
    try:
        count = int(count)
        if count < 1 or count > 10:
            return jsonify({'error': '请求次数必须在1-10之间'}), 400
    except ValueError:
        return jsonify({'error': '无效的请求次数'}), 400
    
    try:
        param = '-n' if os.name == 'nt' else '-c'
        command = ['ping', param, str(count), ip]
        
        result = subprocess.run(
            command, 
            capture_output=True, 
            text=True, 
            timeout=15,
            check=True
        )
        
        return jsonify({'result': result.stdout})
    except subprocess.TimeoutExpired:
        return jsonify({'error': 'Ping操作超时'}), 408
    except subprocess.CalledProcessError as e:
        return jsonify({'error': f'Ping失败: {e.stderr}'}), 400
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@network_bp.route('/portscan', methods=['POST'])
@login_required
def portscan():
    ip = request.form.get('ip', '').strip()
    port = request.form.get('port', '').strip()
    
    if not validate_ip(ip):
        return jsonify({'error': '无效的IP地址'}), 400
    
    try:
        port = int(port)
        if port < 1 or port > 65535:
            return jsonify({'error': '端口号必须在1-65535之间'}), 400
    except ValueError:
        return jsonify({'error': '无效的端口号'}), 400
    
    sock = None
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2.0)
        result = sock.connect_ex((ip, port))
        status = "开放" if result == 0 else "关闭"
        
        return jsonify({
            'result': f"端口 {port} {status}",
            'timestamp': datetime.now().strftime('%H:%M:%S')
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        if sock:
            sock.close()